package com.zzt.java_doc_search.api;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zzt.java_doc_search.searcher.DocSearcher;
import com.zzt.java_doc_search.searcher.Result;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

//import javax.servlet.annotation.WebServlet;
import java.io.IOException;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description
 * User: panda
 * Date: 2025-05-12
 * Time: 20:59
 */
@Slf4j
////这个注解就是在指定当前的路径和哪个 “servlet” 类对应
//@WebServlet("/searcher")
public class DocSearcherServlet extends HttpServlet {

    private static DocSearcher docSearcher = new DocSearcher();

    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1. 先解析请求， 拿到用户提交的查询词
        String query = req.getParameter("query");
        if(query == null || query.equals("")){
            String msg = "您的参数非法！没有获取到 query 的值！";
            log.error(msg);
            resp.sendError(404, msg);
            return;
        }
        //2. 打印记录一下 query 的值
        log.info("query = " + query);
        //3. 调用搜索模块，来进行搜索
        List<Result> results = docSearcher.search(query);
        //4. 把当前的搜索结果进行打包
        resp.setContentType("application/json; charset=utf-8");
        objectMapper.writeValue(resp.getWriter(), results);
    }

}
